package edu.pku.sei.autounit.plugin;

import java.util.HashSet;
import java.util.Set;

import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import edu.pku.sei.autounit.util.Log;

public class InitProject implements IObjectActionDelegate  {

	private IProject project;
	private IJavaProject javaProject;
	
	public static final String CODE_FOLDER = "test";
	public static final IProgressMonitor PROGRESSMONITOR = new NullProgressMonitor();
	
	
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
	}

	
	public void run(IAction action) {
		try {

			IClasspathEntry[] old = javaProject.getRawClasspath();
			Set<IClasspathEntry> set = new HashSet<IClasspathEntry>();
			for (IClasspathEntry ic:old) {
				set.add(ic);
			}
			
			IFolder folder = project.getFolder(new Path(CODE_FOLDER));
			if (!folder.exists())
				folder.create(false, true, PROGRESSMONITOR);
			set.add(JavaCore.newSourceEntry(folder.getFullPath()));
			
			
			SimpleContainer sc = new SimpleContainer();
			for(IClasspathEntry ice:sc.getClasspathEntries())
				set.add(ice);
			
			javaProject.setRawClasspath(set.toArray(new IClasspathEntry[set.size()]),PROGRESSMONITOR);
//			JavaCore.setClasspathContainer(sc.getPath(), 
//					new IJavaProject[]{javaProject}, new IClasspathContainer[]{sc}, PROGRESSMONITOR);
			
		} catch (Exception e) {
			Log.gotUnexpectedExection("InitProject", "run", "",e);
		}
	}

	
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection instanceof TreeSelection) {
			TreeSelection ts = (TreeSelection) selection;
			javaProject = (IJavaProject) ts.getFirstElement();
			project = javaProject.getProject();
		}
		else{
			Log.info("didn't deal with "+selection.getClass().getName());
		}
	}
}
